#!/usr/bin/perl

# thi program generate a excel calendar file.
# one sheet-one month
# one row-one day
#
# simply pass the year at the command line:
#
# ie:
#
#  perl calendar_excel_generator.pl 2010
#


# Copyright (c) Fabrizio Sebastiani <fabrizio@bzimage.it>, 2008
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation 
# files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, 
# subject to the following conditions:

# The above copyright notice and this permission notice shall be i
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGi
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 
# OR OTHER DEALINGS IN THE SOFTWARE.


use Spreadsheet::WriteExcel;
use Date::Manip;

die "pass the year as parameter!" if (@ARGV != 1);


$yy=$ARGV[0];

die "$yy is not a year number" if ($yy !~ /\d+/o );
my $fname = "calendar_$yy.xls";
my $workbook = Spreadsheet::WriteExcel->new($fname);

$hol_format = $workbook->add_format(); # Add a format

$hol_format->set_bold();
$hol_format->set_color('red');
$hol_format->set_align('center');

$work_format = $workbook->add_format(); # Add a format

$work_format->set_color('black');
$work_format->set_align('center');


$d   =ParseDate("$yy-01-01");
$s=$yy+1;
$stop=ParseDate("$s-01-01");
$m_ = -1;
$g_ = -1;

$inc = ParseDateDelta('+1 day');


$flag = 1;
while( $flag ) {
    ($m_,$g_) = ($m,$g);
    ($m,$g) = UnixDate($d,'%m','%d');	
    $flag = Date_Cmp($d,$stop);
   
    if ( $flag != 0) {

	if($m ne $m_) {
	    $worksheet = $workbook->add_worksheet(UnixDate($d,'%b'));
	    $row=0;
	    print "\n $m ->";
	}else {
	    $row++;
	}
	print "$g";
	$hol=UnixDate($d,'%w');
	if($hol == 7 || $hol == 6) {
	    $format=$hol_format;	    
	}else {
	    $format=$work_format;
	}
	$worksheet->write($row, 0, "$g", $format);
	$worksheet->write($row, 1, UnixDate($d,'%a'), $format);		
	$worksheet->set_column(2,2,50)
    }
    $d = DateCalc($d,$inc); # next day
}

print "\n\n";

$workbook->close();

print "generated file: $fname\n\n";
